from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from typing import List, Optional
import time
import logging
import random
from pathlib import Path

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

class SendService:
    def __init__(
        self,
        chrome_path: str,
        cookies: dict,
        wait_time_between_comments: int = 20,
        max_retries: int = 3
    ):
        """
        初始化发送服务
        
        Args:
            chrome_path: Chrome浏览器路径
            cookies: 微博登录所需的cookies字典
            wait_time_between_comments: 发送评论之间的等待时间（秒）
            max_retries: 发送失败时的最大重试次数
        """
        self.chrome_path = chrome_path
        self.cookies = cookies
        self.wait_time_between_comments = wait_time_between_comments
        self.max_retries = max_retries
        self.driver = None

    def setup_driver(self) -> None:
        """设置Chrome浏览器驱动"""
        try:
            chrome_options = Options()
            chrome_options.binary_location = self.chrome_path
            
            # 配置选项
            chrome_options.add_argument('--start-maximized')
            chrome_options.add_argument('--disable-gpu')
            chrome_options.add_argument('--no-sandbox')
            chrome_options.add_argument('--disable-dev-shm-usage')
            chrome_options.add_argument('--disable-notifications')

            service = Service()
            self.driver = webdriver.Chrome(service=service, options=chrome_options)
            logger.info("Chrome浏览器驱动初始化成功")
            
        except Exception as e:
            logger.error(f"设置Chrome驱动时出错: {str(e)}")
            raise

    def add_cookies(self) -> None:
        """添加cookies到浏览器"""
        try:
            self.driver.get("https://m.weibo.cn")
            time.sleep(2)
            
            for name, value in self.cookies.items():
                cookie = {
                    'name': name,
                    'value': value,
                    'domain': '.weibo.cn'
                }
                self.driver.add_cookie(cookie)
            logger.info("Cookie添加成功")
            
            self.driver.refresh()
            time.sleep(2)
            
        except Exception as e:
            logger.error(f"添加Cookie时出错: {str(e)}")
            raise

    def type_with_random_delay(self, element, text: str) -> None:
        """模拟人工输入，每个字符之间有随机延迟"""
        for char in text:
            element.send_keys(char)
            delay = random.uniform(0.1, 0.5)
            time.sleep(delay)

    def send_single_comment(self, comment: str) -> bool:
        """
        发送单条评论
        
        Args:
            comment: 要发送的评论内容
            
        Returns:
            bool: 发送是否成功
        """
        try:
            # 点击发布按钮
            publish_button = WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, "div.lite-iconf.lite-iconf-releas"))
            )
            publish_button.click()
            logger.info("点击发布按钮成功")
            
            # 等待并输入评论
            text_area = WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, "textarea[placeholder='分享新鲜事…']"))
            )
            
            WebDriverWait(self.driver, 10).until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, "textarea[placeholder='分享新鲜事…']"))
            )
            
            text_area.clear()
            self.type_with_random_delay(text_area, comment)
            logger.info(f"评论内容输入成功: {comment[:20]}...")
            
            time.sleep(2)
            
            # 点击发送按钮
            send_button = WebDriverWait(self.driver, 10).until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, "a.m-send-btn"))
            )
            send_button.click()
            logger.info("发送按钮点击成功")
            
            # 等待发送完成
            time.sleep(self.wait_time_between_comments)
            return True
            
        except Exception as e:
            logger.error(f"发送评论时出错: {str(e)}")
            return False

    def send_comments(self, comments: List[str]) -> dict:
        """
        批量发送评论
        
        Args:
            comments: 评论列表
            
        Returns:
            dict: 包含发送结果的统计信息
        """
        if not self.driver:
            self.setup_driver()
            self.add_cookies()
            
        results = {
            "total": len(comments),
            "success": 0,
            "failed": 0,
            "failed_comments": []
        }
        
        for i, comment in enumerate(comments, 1):
            logger.info(f"正在发送第 {i}/{len(comments)} 条评论")
            
            success = False
            for retry in range(self.max_retries):
                if retry > 0:
                    logger.info(f"第 {retry} 次重试发送评论")
                
                if self.send_single_comment(comment):
                    success = True
                    break
                    
                time.sleep(5)  # 重试前等待
            
            if success:
                results["success"] += 1
            else:
                results["failed"] += 1
                results["failed_comments"].append(comment)
                logger.error(f"评论发送失败: {comment[:20]}...")
            
            # 在评论之间添加随机延迟
            if i < len(comments):
                delay = random.uniform(2, 5)
                time.sleep(delay)
        
        return results

    def close(self) -> None:
        """关闭浏览器"""
        if self.driver:
            self.driver.quit()
            logger.info("浏览器已关闭")

def create_send_service(
    chrome_path: Optional[str] = None,
    cookies: Optional[dict] = None,
    wait_time: int = 20
) -> SendService:
    """
    创建发送服务的工厂函数
    
    Args:
        chrome_path: Chrome浏览器路径，如果为None则尝试自动查找
        cookies: 微博登录所需的cookies字典
        wait_time: 发送评论之间的等待时间（秒）
        
    Returns:
        SendService: 配置好的发送服务实例
    """
    if chrome_path is None:
        # 尝试常见的Chrome安装路径
        possible_paths = [
            r"C:\Program Files\Google\Chrome\Application\chrome.exe",
            r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
            str(Path.home() / "AppData/Local/Google/Chrome/Application/chrome.exe")
        ]
        
        for path in possible_paths:
            if Path(path).exists():
                chrome_path = path
                break
                
        if chrome_path is None:
            raise FileNotFoundError("无法找到Chrome浏览器，请手动指定chrome_path")
    
    if cookies is None:
        # 默认cookies，建议从配置文件中读取
        # cookies = {
        #     '_T_WM': '27328921654',
        #     'WEIBOCN_FROM': '1110006030',
        #     'SCF': 'ArwMXo5YJFHh36hYKIsesBG2AamVLcj7yijd15DIvbcHOWZzW22QxVxfAnbzk3d2TcbBb_jAyztPutcRS0JbHEs.',
        #     'SUB': '_2A25FR8UMDeRhGeFL7lIV-SjFyT6IHXVmPVjErDV6PUJbktAYLU-nkW1Nfer9-g5MJlunt4yXdo-EOVcmlv9owvv_',
        #     'SUBP': '0033WrSXqPxfM725Ws9jqgMF55529P9D9W5wv33VdCd0RpFJT9.Dx1_h5JpX5KMhUgL.FoMfSK5X1Kq4eoz2dJLoIpWWUgULdrSX9PiVP0MXehBc',
        #     'SSOLoginState': '1749267804',
        #     'ALF': '1751859804',
        #     'MLOGIN': '1',
        #     'XSRF-TOKEN': 'de9a27',
        #     'M_WEIBOCN_PARAMS': 'oid%3D5174830606844493%26luicode%3D20000174%26uicode%3D20000174',
        #     'mweibo_short_token': '89ff1c2ca8'
        # }
        cookies ={
            '_T_WM': '92068453451',
            'XSRF-TOKEN': 'f22e75',
            'WEIBOCN_FROM': '1110006030',
            'SCF': 'ArwMXo5YJFHh36hYKIsesBG2AamVLcj7yijd15DIvbcHHk1C2vG-VZH4PpH0giU8Bda2GU8Eqg_kUbHSxKHrlA0.',
            'SUB': '_2A25FU_v-DeRhGeFL7lIV-SjFyT6IHXVmEXE2rDV6PUJbktAYLUTxkW1Nfer9-hnhE2DGoAjj_rSSXH7lcdOcpspX',
            'SUBP': '0033WrSXqPxfM725Ws9jqgMF55529P9D9W5wv33VdCd0RpFJT9.Dx1_h5JpX5KMhUgL.FoMfSK5X1Kq4eoz2dJLoIpWWUgULdrSX9PiVP0MXehBc',
            'SSOLoginState': '1750567854',
            'ALF': '1753159854',
            'MLOGIN': '1',
            'mweibo_short_token': '83f59a7498',
            'M_WEIBOCN_PARAMS': 'luicode%3D20000174%26uicode%3D20000174'
        }


    
    return SendService(
        chrome_path=chrome_path,
        cookies=cookies,
        wait_time_between_comments=wait_time
    )

# 使用示例
if __name__ == "__main__":
    # 创建服务实例
    service = create_send_service()
    
    try:
        # 准备要发送的评论列表
        comments = [
            "2025高考加油！",
            "祝所有考生金榜题名！",
            "高考必胜！"
        ]
        
        # 发送评论
        results = service.send_comments(comments)
        
        # 打印结果
        print(f"发送完成！成功: {results['success']}, 失败: {results['failed']}")
        if results['failed_comments']:
            print("发送失败的评论：")
            for comment in results['failed_comments']:
                print(f"- {comment}")
                
    finally:
        service.close()
